package se.ytterman.jpcap.framework.parser;

import java.lang.*;
import java.util.*;

import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.xml.sax.InputSource;

import se.ytterman.jpcap.util.InstanceFactory;

public class ResponseParser {

    public static void parseResponseConfiguration(InputSource inputSource) {
	try {
	    // Create Xpath factory instance
	    XPathFactory xpathFactory = XPathFactory.newInstance();
	    
	    // Create an Xpath object
	    XPath xPath = xpathFactory.newXPath();
	    
	    // Create a nodeset of variable groups
	    String responsePartstExtractor = "/ProtocolConfiguration[@version=\"1.0\"]" +
                                            "/Protocol[@version=\"1.0\"]" +
		                            "/Responses/Response/ResponseFormat/ResponsePart";

	    NodeList responseParts = (NodeList) xPath.evaluate(responsePartstExtractor,
							      inputSource,
							      XPathConstants.NODESET);

	    int partcount = responseParts.getLength();

	    if(false)
		System.out.println("Response nodes: " + partcount);

	    // Iterate over response parts
	    for(int i = 0; i < partcount; i ++) {
		// Fetch parts
		Node partNode = responseParts.item(i);

		String partName = xPath.evaluate("@name", partNode);

		String partDecription = xPath.evaluate("@description", partNode);

		Node producerNode = (Node) xPath.evaluate("ConsumerClass", 
							  partNode,
							  XPathConstants.NODE);
		
		String producerClass = xPath.evaluate("@name", producerNode);


		if(false)
		    System.out.println("Part " + i + " : " + partName + " (" + partDecription + ")" + " [" + producerClass + "]");

		// Extract constructor values
		NodeList responseValues = (NodeList) xPath.evaluate("ResponseValues/Value", 
								    producerNode,
								    XPathConstants.NODESET);
		
		int valuecount = responseValues.getLength();

		// Iterate over all constructor values
		for(int j = 0; j < valuecount; j++) {

		    Node valueNode = responseValues.item(j);

		    String dataType = xPath.evaluate("@datatype", valueNode);
		    String valueString = valueNode.getTextContent();

		    if(false)
			System.out.println("\tValue: " + valueString + " [" + dataType + "]");
		}
	    }
	}
	catch(Exception e) {
	    System.out.println(e + " : " + e.getMessage());
	}
    }
}
